"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Eye } from "lucide-react"
import { GeneralContractListItem } from "@/lib/general-contracts/main/general-contracts-table-columns"

interface VendorGeneralContractReviewTableProps {
  data: GeneralContractListItem[]
}

function getStatusBadge(status: string) {
  const statusLabels: Record<string, string> = {
    'Draft': '임시저장',
    'Request to Review': '조건검토요청',
    'Vendor Replied Review': '협력업체 회신',
    'SHI Confirmed Review': '당사 검토 확정',
    'Contract Accept Request': '계약승인요청',
    'Complete the Contract': '계약체결',
    'Reject to Accept Contract': '계약승인거절',
    'Contract Delete': '계약폐기',
  }

  const statusColors: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
    'Request to Review': 'secondary',
    'Vendor Replied Review': 'default',
    'SHI Confirmed Review': 'default',
  }

  const label = statusLabels[status] || status
  const variant = statusColors[status] || 'outline'

  return <Badge variant={variant}>{label}</Badge>
}

function getFormattedDate(dateString: string | null | undefined) {
  if (!dateString) return "-"
  try {
    return new Intl.DateTimeFormat("ko-KR", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
    }).format(new Date(dateString))
  } catch {
    return "-"
  }
}

function getFormattedDateRange(startDate: string | null | undefined, endDate: string | null | undefined) {
  if (!startDate && !endDate) return "-"
  const start = startDate ? getFormattedDate(startDate) : "-"
  const end = endDate ? getFormattedDate(endDate) : "-"
  return `${start} ~ ${end}`
}

export function VendorGeneralContractReviewTable({ data }: VendorGeneralContractReviewTableProps) {
  const router = useRouter()

  return (
    <Card>
      <CardHeader>
        <CardTitle>조건검토 계약 목록</CardTitle>
      </CardHeader>
      <CardContent className="p-0">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>계약번호</TableHead>
              <TableHead>계약명</TableHead>
              <TableHead>상태</TableHead>
              <TableHead>계약기간</TableHead>
              <TableHead>등록일</TableHead>
              <TableHead>작업</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {data.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
                  조건검토 요청된 계약이 없습니다.
                </TableCell>
              </TableRow>
            ) : (
              data.map((contract) => (
                <TableRow key={contract.id}>
                  <TableCell>
                    <div className="font-medium">
                      {contract.contractNumber}
                      {contract.revision > 0 && (
                        <span className="text-muted-foreground ml-1">
                          (Rev.{contract.revision})
                        </span>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="max-w-[300px] truncate">
                      {contract.name || "-"}
                    </div>
                  </TableCell>
                  <TableCell>
                    {getStatusBadge(contract.status)}
                  </TableCell>
                  <TableCell>
                    {getFormattedDateRange(contract.startDate, contract.endDate)}
                  </TableCell>
                  <TableCell>
                    {getFormattedDate(contract.registeredAt)}
                  </TableCell>
                  <TableCell>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => {
                        router.push(`/partners/general-contract-review/${contract.id}`)
                      }}
                    >
                      <Eye className="h-4 w-4 mr-2" />
                      조회
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  )
}

